import type { VueKeycloakOptions } from '@dsb-norge/vue-keycloak-js/dist/types'
import { keycloakConfig } from '@/config/index'
import { setToken } from '@/utils/auth'
import store from '@/store'

export const keycloakOptions: VueKeycloakOptions = {
  config: {
    url: keycloakConfig.url, // 权限验证地址
    realm: keycloakConfig.realm, // 域
    clientId: keycloakConfig.clientId // 客户端ID
  },
  init: {
    onLoad: 'login-required',
    checkLoginIframe: false
  },
  onReady: (keycloak) => {
    if (keycloak.token) { setToken(keycloak.token) }
    store.dispatch('user/setUserRoles', keycloak.realmAccess?.roles)
    keycloak.loadUserProfile().then(res => {
      store.dispatch('user/setUserInfo', {
        userName: res.username,
        userId: res.id,
        email: res.email,
        name: `${res.lastName} ${res.firstName}`
      })
    })
  },
  onInitError: (error) => {
    // eslint-disable-next-line
    console.log(error, 'Keycloak初始化失败!')
  },
  onAuthRefreshSuccess: (keycloak) => {
    if (keycloak.token) setToken(keycloak.token)
  }
}
